package com.mate.cloud.listener;

import com.google.common.collect.Maps;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.Map;
import java.util.Objects;

/**
 * @description: java类作用描述
 * @author: MI
 * @email: 448341911@qq.com
 * @createTime: 2025/7/3 16:58
 * @updateUser: MI
 * @updateTime: 2025/7/3 16:58
 * @updateRemark: 修改内容
 * @version: 1.0
 */
public class TransactionListenerLocal implements TransactionListener {

    Map<String, Boolean> results = Maps.newHashMap();

    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        System.out.println("开始执行本地事务: " + o.toString());
        String orderId = o.toString();
        // 模拟数据库保持（成功/失败）
        boolean result = Math.abs(Objects.hash(orderId)) % 2 == 0;
        results.put(orderId, result);
        return result ? LocalTransactionState.COMMIT_MESSAGE : LocalTransactionState.UNKNOW;
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        String orderId = messageExt.getKeys();
        System.out.println("执行事务回调检查orderId: " + orderId);
        boolean result = results.get(orderId);
        System.out.println("数据处理结果: " + result);
        return result ? LocalTransactionState.COMMIT_MESSAGE : LocalTransactionState.ROLLBACK_MESSAGE;
    }
}
